package cn.datawin.filter;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.datawin.bean.User;

public class DpsmInterceptor implements HandlerInterceptor{
	
	public static Log log  = LogFactory.getLog("DpsmInterceptor"); 
	static Matcher matcher = new Matcher();
	static String loginPattren = "/index/login";
	static String gettaskPattren = "/task/*";
	static String upcPattren = "/client/*";
	static String copyTask = "/baidu/copytask";
	static String copyTaskhy = "/baidu/copytaskhy";
	static String copybaidusearch = "/baidu/copybaidusearch";
	static String coTask = "/cotask/*";
	
	public static String basePath; 
	public static String getBasePath(HttpServletRequest req){
		if(basePath == null){
			basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath();
		}
		return basePath;
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		request.setCharacterEncoding("UTF-8");
		RequestContext context = RequestContext.begin(request, response);
		String uri = request.getRequestURI();
		uri = uri.substring(request.getContextPath().length());
		log.info(handler +" ["+request.getRemoteHost()+"] -->"+ uri);
		if(matcher.doMatch(loginPattren, uri, true, null)) return true;
		if(matcher.doMatch(gettaskPattren, uri, true, null)) return true;
		if(matcher.doMatch(upcPattren, uri, true, null)) return true;
		if(matcher.doMatch(copyTask, uri, true, null)) return true;
		if(matcher.doMatch(copyTaskhy, uri, true, null)) return true;
		if(matcher.doMatch(copybaidusearch, uri, true, null)) return true;
		if(matcher.doMatch(coTask, uri, true, null)) return true;
		if(context.getUser() == null){
			if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {// ajax请求
				response.setHeader("sessionstatus", "timeout");
				response.getWriter().write("sessiontimeout");
				return false;  //出现bug, 要返回 false
 			}
			response.sendRedirect("/index.html");
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView model) throws Exception {
		//共用的 一些变量 和方法
		RequestContext.get().end();
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		
	}
	
	
	public static class RequestContext{
		public ThreadLocal<RequestContext> local = new ThreadLocal<DpsmInterceptor.RequestContext>();
		
		private HttpSession session;
		private HttpServletRequest req;
		private HttpServletResponse res;
		private Map<String, Cookie> cookies;
		private final static ThreadLocal<RequestContext> contexts = new ThreadLocal<RequestContext>();


		public HttpSession getSession() {
			return session;
		}

		public HttpServletRequest getRequest() {
			return req;
		}

		public HttpServletResponse getResponse() {
			return res;
		}

		public Map<String, Cookie> getCookies() {
			return cookies;
		}
		
		public User getUser() {
			return (User) session.getAttribute("user");
		}
		
		public RequestContext(HttpServletRequest req, HttpServletResponse res) {
			this.req = req;
			this.res = res;
			this.session = req.getSession(); // req.getSession(false) 默认不创建session
			this.cookies = new HashMap<String, Cookie>();
			Cookie[] cookies = req.getCookies();
			if (cookies != null)
				for (Cookie ck : cookies) {
					this.cookies.put(ck.getName(), ck);
				}
		}

		public static RequestContext begin(HttpServletRequest req, HttpServletResponse res) {
			RequestContext rc = new RequestContext(req, res);
			contexts.set(rc);
			return rc;
		}

		public static RequestContext get() {
			return contexts.get();
		}
		
		public void end() {
			this.req = null;
			this.res = null;
			this.session = null;
			this.cookies = null;
			contexts.remove();
		}
		
	}
	
	static class Matcher extends AntPathMatcher{
		@Override
		protected boolean doMatch(String pattern, String path, boolean fullMatch, Map<String, String> uriTemplateVariables) {
			return super.doMatch(pattern, path, fullMatch, uriTemplateVariables);
		}
	}


}
